package managedbean.CRM.SaleQuotation;

import entity.CRM.Customer;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import entity.CRM.LineItem;
import entity.CRM.ProductPrice;
import entity.CRM.SaleLead;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import session.stateless.CRM.CustomerBeanLocal;
import session.stateless.CRM.DiscountBeanLocal;
import session.stateless.CRM.ProductPriceBeanLocal;
import session.stateless.CRM.SaleInquiryBeanLocal;
import session.stateless.CRM.SaleLeadBeanLocal;
import session.stateless.CRM.SaleQuotationBeanLocal;

@ManagedBean(name="saleQuotationManagerBean")
@ViewScoped
public class AddSaleQuotationManagerBean implements Serializable{
    public AddSaleQuotationManagerBean() {}
    
    @EJB
    private SaleQuotationBeanLocal saleQuotationBeanLocal;
    @EJB
    private SaleInquiryBeanLocal saleInquiryBeanLocal;
    @EJB
    private SaleLeadBeanLocal saleLeadBeanLocal;
    @EJB
    private CustomerBeanLocal customerBeanLocal;
    @EJB
    private DiscountBeanLocal discountBeanLocal;
    @EJB
    private ProductPriceBeanLocal productBeanLocal;
    
    private Long salequiryId;
    private String saleLeadName;
    private String registrationNumber;    
    private List<LineItem> lineItems;
    private List<Integer> quantity;
    private List<Double> prices;
    private Integer leadTime;
    private Integer validityPeriod;
    private Double customDiscount;
    private Double finalPrice;
    
    private String statusMessage;
    

    public void initView(PhaseEvent event){
        try{
            if(lineItems == null)
            {
                lineItems = new ArrayList<LineItem>();
                
                LineItem lineItem_A = new LineItem();
                lineItem_A.setProductPrice(productBeanLocal.getFirstProductPriceA());                
                lineItem_A.setFinalPrice(new Double(0));
                lineItem_A.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_A);
                
                LineItem lineItem_B = new LineItem();
                lineItem_B.setProductPrice(productBeanLocal.getFirstProductPriceB());
                lineItem_B.setFinalPrice(new Double(0));
                lineItem_B.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_B);
                
                LineItem lineItem_C = new LineItem();
                lineItem_C.setProductPrice(productBeanLocal.getFirstProductPriceC());
                lineItem_C.setFinalPrice(new Double(0));
                lineItem_C.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_C);
                
                LineItem lineItem_D = new LineItem();
                lineItem_D.setProductPrice(productBeanLocal.getFirstProductPriceD());
                lineItem_D.setFinalPrice(new Double(0));
                lineItem_D.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_D);
                
                this.setLineItems(lineItems);     
                this.setFinalPrice(new Double(0));
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    public void initView2(PhaseEvent event){
        try
        {
            if(registrationNumber==null){
                SaleLead saleLead = (SaleLead)FacesContext.getCurrentInstance().getExternalContext().getFlash().get("selectedSaleLead");
                registrationNumber = saleLead.getRegistrationNumber();
                saleLeadName = saleLead.getSaleLeadName();
            }
            
            if(lineItems == null)
            {
                lineItems = new ArrayList<LineItem>();
                
                LineItem lineItem_A = new LineItem();
                lineItem_A.setProductPrice(productBeanLocal.getFirstProductPriceA());                
                lineItem_A.setFinalPrice(new Double(0));
                lineItem_A.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_A);
                
                LineItem lineItem_B = new LineItem();
                lineItem_B.setProductPrice(productBeanLocal.getFirstProductPriceB());
                lineItem_B.setFinalPrice(new Double(0));
                lineItem_B.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_B);
                
                LineItem lineItem_C = new LineItem();
                lineItem_C.setProductPrice(productBeanLocal.getFirstProductPriceC());
                lineItem_C.setFinalPrice(new Double(0));
                lineItem_C.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_C);
                
                LineItem lineItem_D = new LineItem();
                lineItem_D.setProductPrice(productBeanLocal.getFirstProductPriceD());
                lineItem_D.setFinalPrice(new Double(0));
                lineItem_D.setVolumeDiscountRate(new Double(0));
                lineItems.add(lineItem_D);
                
                this.setLineItems(lineItems);
                this.setFinalPrice(new Double(0));
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public Double getCustomDiscount() {
        return customDiscount;
    }

    public void setCustomDiscount(Double customDiscount) {
        this.customDiscount = customDiscount;
    }

    public Double getFinalPrice() {
        return finalPrice;
    }

    public void setFinalPrice(Double finalPrice) {
        this.finalPrice = finalPrice;
    }
    
    public List<Integer> getQuantity() {
        return quantity;
    }
    public void setQuantity(List<Integer> quantity) {
        this.quantity = quantity;
    }

    public String getSaleLeadName() {
        return saleLeadName;
    }

    public void setSaleLeadName(String saleLeadName) {
        this.saleLeadName = saleLeadName;
    }
    
    public List<Double> getPrices(){
        return prices;
    }
    public void setPrice(List<Double> prices){
        //send to discountmodule to get final price;
        this.prices = prices;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }

    public void setRegistrationNumber(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public Long getSalequiryId() {
        return salequiryId;
    }

    public Integer getValidityPeriod() {
        return validityPeriod;
    }

    public void setValidityPeriod(Integer validityPeriod) {
        this.validityPeriod = validityPeriod;
    }
    
    public void setSalequiryId(Long salequiryId) {
        this.salequiryId = salequiryId;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }
    
    public List<LineItem> getLineItems() {
        return lineItems;
    }
    public void setLineItems(List<LineItem> lineItems) {
        this.lineItems = lineItems;
    }
    
    public List<ProductPrice> getProductPrice(){
        return saleInquiryBeanLocal.getProductPrice();
    }
    
    public void setLeadTime(Integer leadTime){
        //Call the method from MRP to get the leadTime according to the lineItems;
        this.leadTime = leadTime;
    }
    public Integer getLeadTime(){
        return leadTime;
    }
    
    public void saveSaleQuotation(ActionEvent event) {
        System.out.println(saleLeadName);
        try {
            if (saleLeadBeanLocal.findByName(saleLeadName) == null) {
                statusMessage = "Sale Lead does not exist";
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                        "Add New Sale Quotation Result: Unsuccessful" + statusMessage + "", ""));
            }
            else
            {
                List<LineItem> lineItemList = new ArrayList<LineItem>();
                LineItem temp_lineItem = new LineItem();
                for (int i = 0; i < lineItems.size(); i++) {
                    if ((lineItems.get(i).getLineItemQuantity() != null) &&(lineItems.get(i).getLineItemQuantity()>0)) 
                        {
                            lineItems.get(i).setProductPrice(productBeanLocal.lookupRange(lineItems.get(i).getProductPrice().getProductType(), lineItems.get(i).getLineItemQuantity()));
                            temp_lineItem = saleInquiryBeanLocal.createLineItem_VolumeCustomDiscountIncluded(lineItems.get(i).getProductPrice(), lineItems.get(i).getLineItemQuantity(), customDiscount);
                            lineItemList.add(temp_lineItem);
                        }
                }
                Long saleQuotationId = saleQuotationBeanLocal.createNewSaleQuotation(saleLeadName, lineItemList, new Integer(0), validityPeriod, customDiscount);
                statusMessage = "New Sale Quotation Saved Successfully";
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                        "Add New Sale Quotation Result:" + statusMessage + "(New Sale Quotation ID is:" + saleQuotationId + ")", ""));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public List<String> complete(String query) {  
        List<String> results = new ArrayList<String>();  
        
        List<SaleLead> list = saleLeadBeanLocal.getSalesLead();
        List<Customer> list2 = customerBeanLocal.getCustomers();
        
        for (int i = 0; i < list.size(); ++i)
        {
            if (list.get(i).getSaleLeadName().toLowerCase().contains(query.toLowerCase()))
                results.add(list.get(i).getSaleLeadName());
        }
        
        for (int i = 0; i < list2.size(); ++i)
        {
            if (list2.get(i).getSaleLeadName().toLowerCase().contains(query.toLowerCase()))
                results.add(list2.get(i).getSaleLeadName());
        }
        return results;  
    }
    
    public void calculate(ActionEvent event)
    {
           Long temp_quantity_A = lineItems.get(0).getLineItemQuantity();
           if (temp_quantity_A==null) temp_quantity_A=new Long(0);
           ProductPrice temp_product_A=productBeanLocal.lookupRange("A", temp_quantity_A);
           lineItems.get(0).setProductPrice(temp_product_A);
           double temp_discount_A=discountBeanLocal.calculateDiscountRate("A", temp_quantity_A);
           lineItems.get(0).setVolumeDiscountRate(temp_discount_A);
           Double temp_price_A=temp_product_A.getProductPrice()*temp_quantity_A* (1-(customDiscount+temp_discount_A)/100);
           lineItems.get(0).setFinalPrice(temp_price_A);
           
           Long temp_quantity_B = lineItems.get(1).getLineItemQuantity();
           if (temp_quantity_B==null) temp_quantity_B=new Long(0);
           ProductPrice temp_product_B=productBeanLocal.lookupRange("B", temp_quantity_B);
           lineItems.get(1).setProductPrice(temp_product_B);
           double temp_discount_B=discountBeanLocal.calculateDiscountRate("B", temp_quantity_B);
           lineItems.get(1).setVolumeDiscountRate(temp_discount_B);
           Double temp_price_B=temp_product_B.getProductPrice()*temp_quantity_B* (1-(customDiscount+temp_discount_B)/100);
           lineItems.get(1).setFinalPrice(temp_price_B);
           
           Long temp_quantity_C = lineItems.get(2).getLineItemQuantity();
           if (temp_quantity_C==null) temp_quantity_C=new Long(0);
           ProductPrice temp_product_C=productBeanLocal.lookupRange("C", temp_quantity_C);
           lineItems.get(2).setProductPrice(temp_product_C);
           double temp_discount_C=discountBeanLocal.calculateDiscountRate("C", temp_quantity_C);
           lineItems.get(2).setVolumeDiscountRate(temp_discount_C);
           Double temp_price_C=temp_product_C.getProductPrice()*temp_quantity_C* (1-(customDiscount+temp_discount_C)/100);
           lineItems.get(2).setFinalPrice(temp_price_C);
           
           Long temp_quantity_D = lineItems.get(3).getLineItemQuantity();
           if (temp_quantity_D==null) temp_quantity_D=new Long(0);
           ProductPrice temp_product_D=productBeanLocal.lookupRange("D", temp_quantity_D);
           lineItems.get(3).setProductPrice(temp_product_D);
           double temp_discount_D=discountBeanLocal.calculateDiscountRate("D", temp_quantity_D);
           lineItems.get(3).setVolumeDiscountRate(temp_discount_D);
           Double temp_price_D=temp_product_D.getProductPrice()*temp_quantity_D* (1-(customDiscount+temp_discount_D)/100);
           lineItems.get(3).setFinalPrice(temp_price_D);
           
           Double temp_Price=0.0;
           for (LineItem e:lineItems)
           {
               temp_Price+=e.getFinalPrice();
           }
           this.setFinalPrice(temp_Price);
    }
}
